package rpc

import (
	net "gitee.com/ameise84/e3net"
)

const _rpcTag = "node_rpc"

type service struct {
	opts *Options
	addr string
	srv  net.TcpServer
	agt  net.TcpAgent
}

func (ts *service) start(opts *Options) (addr string, err error) {
	defer func() {
		if err != nil {
			if ts.agt != nil {
				ts.agt.Stop()
				ts.agt = nil
			}
			if ts.srv != nil {
				ts.srv.RemoveAcceptor(_rpcTag)
				ts.srv.Stop()
				ts.srv = nil
			}

		}
	}()
	ts.opts = opts
	var ip, port string
	if ip, port, err = net.SplitHostPort(opts.addr); err != nil {
		return
	}
	if ip == "" {
		ip = net.GetInternalIP()
	}
	//没有指定端口,默认分配
	if port == "" {
		port = "0"
	}

	ts.srv = net.NewTcpServer()

	if ts.addr, err = ts.srv.AddAcceptor(_srvHandler, _rpcTag, ip+":"+port, false, net.DefaultTcpAcceptorOptions().SetReadTimeout(opts.readTimeout).SetWriteTimeout(opts.writeTimeout)); err != nil {
		return
	}

	if err = ts.srv.Start(); err != nil {
		return
	}

	if ts.agt, err = net.NewTcpAgent(_agtHandler, net.DefaultTcpAgentOptions().SetReadTimeout(0).SetWriteTimeout(opts.writeTimeout)); err != nil {
		return
	}

	if err = ts.agt.Start(); err != nil {
		return
	}
	return ts.addr, err
}

func (ts *service) stop() {
	if ts.agt != nil {
		ts.agt.Stop()
		ts.agt = nil
	}
	if ts.srv != nil {
		ts.srv.RemoveAcceptor(_rpcTag)
		ts.srv.Stop()
		ts.srv = nil
	}
}

func (ts *service) Address() string {
	return ts.addr
}
